package com.jxs.android.ges;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;

import com.jxs.android.ges.util.Utils;
import com.jxs.android.weiget.BuAlertDailog;

public class Welcome extends Activity {

	private int logoDelay = 2 * 1000;
	private AnimationDrawable animation;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.logo);

		animation = (AnimationDrawable) findViewById(R.id.loading).getBackground();

		new Handler().postDelayed(startRunnable, logoDelay);
	}

	@Override
	protected void onStart() {
		super.onStart();
		(new Timer(false)).schedule(new AnimationTimer(animation), 100);
	}

	private static class AnimationTimer extends TimerTask {
		AnimationDrawable animation;

		public AnimationTimer(AnimationDrawable animation) {
			this.animation = animation;
		}

		@Override
		public void run() {
			animation.start();
			this.cancel();
		}
	}

	private Runnable startRunnable = new Runnable() {
		@Override
		public void run() {
			logoNext();
		}
	};

	private void logoNext() {
		boolean netAvailable = Utils.isNetAvailable(this);
		if (netAvailable) {
			startApp();
		} else {
			Utils.setNetWork(this, new BuAlertDailog.AlertOkAndCancelListener() {

				@Override
				public void okLogic(Dialog dialog) {
					dialog.cancel();
					startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), REQ_NET_SETTING);
				}

				@Override
				public String getOkText(Context context) {
					return "设置";
				}

				@Override
				public String getCancleText(Context context) {
					return "取消";
				}

				@Override
				public void cancelLogic(Dialog dialog) {
					dialog.cancel();
					Welcome.this.finish();
				}
			});
		}
	}

	private static final int REQ_NET_SETTING = 0x008;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQ_NET_SETTING) {
			startApp();
		}
	}

	private void startApp() {
		Intent intent = new Intent(Welcome.this, Login.class);
		startActivity(intent);
		Welcome.this.finish();
	}

}